package initialize

import (
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

var Logger *zap.Logger

func initLogger() {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   Config.Logger.Filename,
		MaxSize:    Config.Logger.MaxSize,
		MaxBackups: Config.Logger.MaxBackups,
		MaxAge:     Config.Logger.MaxAge,
	}
	// 写入文件
	fileWriteSyncer := zapcore.AddSync(lumberJackLogger)
	// 控制台写入器
	consoleWriteSyncer := zapcore.AddSync(os.Stdout)

	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder
	encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder

	// 文件写入用 JSON
	fileEncoder := zapcore.NewJSONEncoder(encoderConfig)

	// 简单编码器用于控制台，可以根据需要调整
	consoleEncoder := zapcore.NewConsoleEncoder(encoderConfig)

	var l = new(zapcore.Level)
	err := l.UnmarshalText([]byte(Config.Logger.Level))
	if err != nil {
		panic("init logger err:" + err.Error())
	}

	fileCore := zapcore.NewCore(fileEncoder, fileWriteSyncer, l)
	consoleCore := zapcore.NewCore(consoleEncoder, consoleWriteSyncer, l)

	core := zapcore.NewTee(fileCore, consoleCore)

	Logger = zap.New(core, zap.AddCaller())
}
